package com.mt.controller;

import com.google.common.collect.Maps;
import com.mt.ChannelAdminConstant;
import com.mt.channel.entity.ChannelAdminEntity;
import com.mt.channel.entity.ChannelCustomerEntity;
import com.mt.channel.feign.ChannelCustomerFeign;
import com.mt.common.ServiceResult;
import com.mt.common.entity.QueryPageBean;
import com.mt.common.util.ConvertUtil;
import com.mt.common.util.EncryptUtil;
import com.mt.common.util.StringUtil;
import com.mt.customer.constants.CustomerConstant;
import com.mt.customer.entity.CustomerEntity;
import com.mt.customer.feign.CustomerFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/channelAdminCustomer")
public class ChannelCustomerAPIController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ChannelCustomerFeign channelCustomerFeign;

    @Autowired
    CustomerFeign customerFeign;

    // 查询
    @PostMapping("/findList")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> list(@RequestBody QueryPageBean queryPageBean) {
        long startTime1 = System.currentTimeMillis(); // 获取开始时间
        Map<String, Object> result = Maps.newHashMap();
        // if(redisTemplate.hasKey("666")){
        // List<ChannelCustomerEntity> o = (List<ChannelCustomerEntity>)
        // redisTemplate.opsForValue().get("666");
        // long endTime1 = System.currentTimeMillis(); //获取结束时间
        // System.out.println("代码运行时间：" + (endTime1 - startTime1) + "ms"); //输出程序运行时间
        // result.put("count", 128);
        // result.put("code", 0);
        // result.put("data", o);
        // return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        // }
        long startTime2 = System.currentTimeMillis(); // 获取开始时间
        Map<String, Object> params = queryPageBean.getMap();
        params.put("channelId", 1);
        params.put("withCustomerCourseCount", true);
        ServiceResult<List<ChannelCustomerEntity>> list = channelCustomerFeign.findList(params,
                queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        long endTime2 = System.currentTimeMillis(); // 获取结束时间

        List<ChannelCustomerEntity> result1 = list.getResult();
        // redisTemplate.opsForValue().set("666",result1);

        result.put("count", list.getPager().getRowsCount());
        result.put("code", 0);
        result.put("data", result1);

        System.out.println("代码运行时间：" + (endTime2 - startTime2) + "ms"); // 输出程序运行时间
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }

    @RequestMapping("/findInfo")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> findInfo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = Maps.newHashMap();
        Map<String, Object> params = null;
        ChannelCustomerEntity channelCustomerEntity = null;
        ServiceResult<ChannelCustomerEntity> channelCustomerResult = null;
        Integer customerId = ConvertUtil.toInt(request.getParameter("customerId"), 0);
        try {
            if (customerId == 0) {
                result.put("code", 1);
                result.put("msg", "查询参数不正确！");
                return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
            }
            params = new HashMap<String, Object>();
            params.put("customerId", customerId);
            params.put("channelId", 1);
            channelCustomerResult = channelCustomerFeign.findInfo(params);
            if (channelCustomerResult.getSuccess() && channelCustomerResult.getResult() != null) {
                channelCustomerEntity = channelCustomerResult.getResult();
            }
            if (channelCustomerEntity == null) {
                result.put("code", 1);
                result.put("msg", "用户信息不存在！");
                return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
            }
            result.put("code", 0);
            result.put("msg", "");
            result.put("data", channelCustomerEntity);
        } catch (Exception e) {

        }
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }

    @PostMapping("/editPost")
    public ResponseEntity<Map<String, Object>> editPost(@RequestBody ChannelCustomerEntity channelCustomerEntity,
            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = Maps.newHashMap();
        Map<String, Object> params = null;
        Integer customerId = ConvertUtil.toInt(channelCustomerEntity.getCustomerId(), 0);
        ChannelCustomerEntity updateChannelCustomerEntity = null;
        ServiceResult<Integer> editResult = null;
        CustomerEntity customerEntity = null;
        Date now = new Date();
        try {
            if (channelCustomerEntity.getLoginName() == null) {
                result.put("code", ChannelAdminConstant.FAILURE);
                result.put("msg", "用户名!");
            }
            String ecSalt = StringUtil.randomStr(6, 0);
            if (customerId > 0) {
                params = new HashMap<String, Object>();
                params.put("channelId", 1);
                params.put("customerId", customerId);
                ServiceResult<ChannelCustomerEntity> channelCustomerResult = channelCustomerFeign.findInfo(params);
                if (channelCustomerResult.getSuccess() && channelCustomerResult.getResult() != null) {
                    updateChannelCustomerEntity = channelCustomerResult.getResult();
                }
                if (updateChannelCustomerEntity != null) {
                    updateChannelCustomerEntity.setRealName(channelCustomerEntity.getRealName());
                    updateChannelCustomerEntity.setAge(channelCustomerEntity.getAge());
                    updateChannelCustomerEntity.setSex(channelCustomerEntity.getSex());
                    if (!channelCustomerEntity.getPassword().equals(updateChannelCustomerEntity.getPassword())) {
                        updateChannelCustomerEntity.setPassword(channelCustomerEntity.getPassword());
                    } else {
                        updateChannelCustomerEntity.setPassword(
                                EncryptUtil.md5(EncryptUtil.md5(channelCustomerEntity.getPassword()) + ecSalt));
                        updateChannelCustomerEntity.setEcSalt(ecSalt);
                    }
                    updateChannelCustomerEntity.setUpdateTime(now);
                    editResult = channelCustomerFeign.doUpdate(updateChannelCustomerEntity);
                } else {
                    customerId = 0;
                }
            }
            if (customerId == 0) {
                params = new HashMap<String, Object>();
                params.put("loginName", channelCustomerEntity.getLoginName());
                params.put("channelId", 1);
                ServiceResult<ChannelCustomerEntity> channelCustomerResult = channelCustomerFeign.findInfo(params);
                if (channelCustomerResult.getSuccess() && channelCustomerResult.getResult() != null) {
                    updateChannelCustomerEntity = channelCustomerResult.getResult();
                }
                if (updateChannelCustomerEntity != null) {
                    result.put("code", ChannelAdminConstant.FAILURE);
                    result.put("msg", "当前学员数据已经存在");
                    return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
                }
                params = new HashMap<String, Object>();
                params.put("loginName", channelCustomerEntity.getLoginName());
                params.put("status", CustomerConstant.CUSTOMER_STATUS_1);
                ServiceResult<List<CustomerEntity>> customerResult = customerFeign.findList(params, 0, 0);
                if (customerResult.getSuccess() && customerResult.getResult() != null
                        && customerResult.getResult().size() > 0) {
                    List<CustomerEntity> customerList = customerResult.getResult();
                    customerEntity = customerList.get(0);
                }

                if (customerEntity == null) {
                    customerEntity = new CustomerEntity();
                    customerEntity.setPassword(
                            EncryptUtil.md5(EncryptUtil.md5(channelCustomerEntity.getPassword()) + ecSalt));
                    customerEntity.setMobile(channelCustomerEntity.getLoginName());
                    customerEntity.setUserAge(channelCustomerEntity.getAge());
                    customerEntity.setLoginName(channelCustomerEntity.getLoginName());
                    customerEntity.setMobile(channelCustomerEntity.getLoginName());
                    customerEntity.setSex(channelCustomerEntity.getSex());
                    customerEntity.setCreateTime(now);
                    customerEntity.setUpdateTime(now);
                    customerEntity.setChannelUser(1);
                    customerEntity.setStatus(CustomerConstant.CUSTOMER_STATUS_1);
                    customerEntity.setNickname(channelCustomerEntity.getRealName());
                    customerEntity.setRealName(channelCustomerEntity.getRealName());
                    customerEntity.setIsCrmSyn(CustomerConstant.IS_CRM_SYN_0);
                    customerEntity.setCustomerSource(CustomerConstant.CUSTOMER_SOURCE_0);
                    customerEntity.setEcSalt(ecSalt);
                    editResult = customerFeign.doInsert(customerEntity);
                    if (editResult.getSuccess() && editResult.getResult() != null && editResult.getResult() > 0) {
                        customerId = editResult.getResult();
                        customerEntity.setCustomerId(customerId);
                        this.addChannelCustomer(customerEntity);
                    }
                } else {
                    editResult = new ServiceResult<Integer>();
                    editResult.setSuccess(true);
                    customerEntity.setSex(channelCustomerEntity.getSex());
                    customerEntity.setUserAge(channelCustomerEntity.getAge());
                    customerEntity.setRealName(channelCustomerEntity.getRealName());
                    customerEntity.setEcSalt(ecSalt);
                    customerEntity.setPassword(
                            EncryptUtil.md5(EncryptUtil.md5(channelCustomerEntity.getPassword()) + ecSalt));
                    this.addChannelCustomer(customerEntity);
                }
            }
            if (editResult != null && editResult.getSuccess()) {
                result.put("code", ChannelAdminConstant.SUCCESS);
                result.put("msg", "编辑用户成功");
            } else {
                result.put("code", ChannelAdminConstant.FAILURE);
                result.put("msg", "保存用户错误!");
            }
        } catch (Exception e) {
        }

        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }

    public void addChannelCustomer(CustomerEntity customerEntity) {
        ChannelCustomerEntity channelCustomerEntity = new ChannelCustomerEntity();
        Date date = new Date();
        try {
            Integer customerId = customerEntity.getCustomerId();
            channelCustomerEntity.setCustomerId(customerId);
            channelCustomerEntity.setLoginName(customerEntity.getLoginName());
            channelCustomerEntity.setChannelAdminId(1);
            channelCustomerEntity.setChannelId(1);
            channelCustomerEntity.setCreateTime(date);
            channelCustomerEntity.setUpdateTime(date);
            channelCustomerEntity.setChannelCommissionerId(1);
            channelCustomerEntity.setChannelManagerId(0);
            channelCustomerEntity.setChannelDirectorId(0);
            channelCustomerEntity.setPassword(customerEntity.getPassword());
            channelCustomerEntity.setChannelNo("bkt_channel");
            channelCustomerEntity.setSex(customerEntity.getSex());
            channelCustomerEntity.setAge(customerEntity.getUserAge());
            channelCustomerEntity.setRealName(customerEntity.getRealName());
            channelCustomerEntity.setEcSalt(customerEntity.getEcSalt());
            channelCustomerFeign.doInsert(channelCustomerEntity);
        } catch (Exception e) {

        }
    }

}
